//
//  LFBIphoneScanQRCodeController.m
//  loveFreshBeen
//
//  Created by Feng on 2017/7/11.
//  Copyright © 2017年 feng. All rights reserved.
//

#import "LFBIphoneScanQRCodeController.h"
#import <AVFoundation/AVFoundation.h>

@interface LFBIphoneScanQRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong, nonatomic)   AVCaptureInput *videoInput;

@property (strong, nonatomic)   AVCaptureSession *session;

@property (strong, nonatomic)   AVCaptureMetadataOutput *metaOutput;

@end

@implementation LFBIphoneScanQRCodeController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.1 创建摄像头设备对象
    AVCaptureDevice *videoVideo = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoVideo error:nil];
    
    // 2. 创建输出 -> Metadata 二维码识别，条形码识别，人脸识别等等
    self.metaOutput = [AVCaptureMetadataOutput new];
    
    // 3. 创建 session
    self.session = [AVCaptureSession new];
    
    
    // 4. 关联输入和输入
    if([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    
    if([self.session canAddOutput:self.metaOutput]) {
        [self.session addOutput:self.metaOutput];
    }
    
    // 必须代码设置代理时添加session中以后
    // 设置识别类型
    self.metaOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    [self.metaOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 5. 设置预览
    AVCaptureVideoPreviewLayer *previewPlayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    previewPlayer.frame = self.view.bounds;
    [self.view.layer addSublayer:previewPlayer];
    
    // 6. 开始启动
    [self.session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate -
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
        NSLog(@"%@",obj.stringValue);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:obj.stringValue]];
    }
}

@end
